package bb.lanxing.calc.manager;

import android.database.Cursor;
import android.location.Location;
import android.text.TextUtils;

import com.github.mikephil.charting.utils.Utils;

import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.sport.ISportItem;
import bb.lanxing.utils.PanelItemTypeUtil;
import gov.nist.core.Separators;
import bb.lanxing.App;
import bb.lanxing.calc.data.CadencePoint;
import bb.lanxing.calc.data.DisplayPoint;
import bb.lanxing.calc.data.GpsPoint;
import bb.lanxing.calc.data.HeartratePoint;
import bb.lanxing.calc.data.PowerratePoint;
import bb.lanxing.calc.data.BiketrainerPoint;
import bb.lanxing.calc.data.IndoorbikePoint;
import bb.lanxing.calc.data.CrosstrainerPoint;
import bb.lanxing.calc.data.RowerPoint;
import bb.lanxing.calc.data.SourcePoint;
import bb.lanxing.manager.RemoteSharedPreference;
import bb.lanxing.model.WorkoutDatabaseHelper;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.model.database.User;
import bb.lanxing.model.database.Workout;
import bb.lanxing.util.CyclingPowerUtil;
import bb.lanxing.util.DurationUtil;
import bb.lanxing.util.Log;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import bb.lanxing.network.NetSubscribe;
import bb.lanxing.network.ThirdPartyClient;
import bb.lanxing.model.json.WeatherData;
import bb.lanxing.manager.SPConstant;

/**
 * 数据转化类，将 SourcePoint 转化为 DisplayPoint
 */
public class SourceDataPool {
    //{1, 0, 5, 2, 3, 11, 13, 12, 38, 26, 18, 19, 20, 35, 21, 22, 23, 39, 6};
    public static final int[] DEFAULT_TYPES =
            {
                    //0, 1, 2, 3, 5, 6, 11, 12, 13, 18, 19, 20, 21, 22, 23, 26, 35, 38, 39
                    ISportItem.DATA_TYPE_DISTANCE,
                    ISportItem.DATA_TYPE_SPEED,
                    ISportItem.DATA_TYPE_AVG_SPEED,
                    ISportItem.DATA_TYPE_MAX_SPEED,
                    ISportItem.DATA_TYPE_DURATION,
                    ISportItem.DATA_TYPE_TOTAL_DURATION,

                    ISportItem.DATA_TYPE_ALTITUDE,
                    ISportItem.DATA_TYPE_GRADIENT,
                    ISportItem.DATA_TYPE_ELEVATION_GAIN,
                    ISportItem.DATA_TYPE_CADENCE,
                    ISportItem.DATA_TYPE_AVG_CADENCE,
                    ISportItem.DATA_TYPE_MAX_CADENCE,
                    ISportItem.DATA_TYPE_HEART_RATE,
                    ISportItem.DATA_TYPE_AVG_HEART_RATE,
                    ISportItem.DATA_TYPE_MAX_HEART_RATE,
                    ISportItem.DATA_TYPE_POWER,
                    ISportItem.DATA_TYPE_POWER_TSS,
                    ISportItem.DATA_TYPE_AVG_POWER,
                    ISportItem.DATA_TYPE_MAX_POWER,
                    ISportItem.DATA_TYPE_POWER_3_SECONDS,
                    ISportItem.DATA_TYPE_POWER_10_SECONDS,
                    ISportItem.DATA_TYPE_TEMPERATURE,
                    ISportItem.DATA_TYPE_CALORIE,
                    ISportItem.DATA_TYPE_STEP
            };
    private static final String TAG = "SourceDataPool";
    private Float accuracy;
    private Double altitude;
    private Float avg10sPower;
    private Float avg30sPower;
    private Float avg3sPower;
    private Integer avgCadence;
    private Float avgElevationGain;
    private Float avgElevationLoss;
    private Integer avgHeartrate;
    private Float avgPower;
    private Double avgSpeed;
    private Integer azimuth;
    private Integer cadence;
    private Integer calorie;
    private Float direction;
    private Double distance;
    private Long duration;
    private Float elevationGain;
    private SourceDataItem elevationGainItem;
    private Float elevationLoss;
    private SourceDataItem elevationLossItem;
    private Float grade;
    private Integer heartrate;
    private Float heartrateLTHT;
    private Integer heartrateWarn;
    private boolean initialized;
    private Location location;
    private Double maxAltitude;
    private Integer maxCadence;
    private Float maxElevationGain;
    private Float maxElevationLoss;
    private Integer maxHeartRateWarning;
    private Integer maxHeartrate;
    private Float maxHeartratePer;
    private Float maxPower;
    private Double maxSpeed;
    private Float maxTemperature;
    private Double minAltitude;
    private Float minTemperature;
    private SourceDataItem np4PowerItem;
    private Long pauseDuration;
    private Float power;
    private Float biketrainerpower;
    private ArrayList<PowerDataItem> powerDataList;
    private Float powerFTP;
    private Float powerFTPPer;
    private SourceDataItem powerItem;
    private Float powerNP;
    private Integer powerSectionCount;
    private Float powerSectionNP;
    private Float powerTSS;
    private Long powerTimeNP;
    private Float pressure;
    private Double speed;
    private Integer steps;
    private Integer indoorbikeresistancelevel;
    private Integer indoorbikeenergy;
    private Integer indoorbikeheartrate;
    private Double indoorbiketotaldistance;
    private Integer crosstrainerresistancelevel;
    private Integer crosstrainerstride;
    private Integer crosstrainersteprate;
    private Integer crosstrainerenergy;
    private Double crosstrainertotaldistance;
    private Integer rowerstrokerate;
    private Integer roweravgstrokerate;
    private Integer rowerstrokecount;
    private Double rowertotaldistance;
    private Double rowerpace;
    private Double roweravgpace;
    private Integer rowerpower;
    private Integer roweravgpower;
    private Integer rowerresistancelevel;
    private Integer rowerenergy;
    private Float temperature;
    private Double totalAvgSpeed;
    private Long totalDuration;
    private long typesSwitch;

    public SourceDataPool(int[] dataTypes) {
        for (int i : dataTypes) {
            checkSportType(i);
            typesSwitch |= 1L << i;
        }
        initialized = false;
    }

    public void update(SourcePoint sourcePoint, Workout workout) {
//        Float f = 0.0f;
        Float f2;
        Float f3;
        if (!initialized) {
            return;
        }
        clearRealtimeData();
        Log.d(TAG, "update...");
        if (workout != null) {
            if (hasType(ISportItem.DATA_TYPE_DISTANCE)) {
                distance = workout.getDistance();
            }
            if (hasType(ISportItem.DATA_TYPE_AVG_SPEED)) {
                avgSpeed = workout.getAvgSpeed();
            }
            if (hasType(ISportItem.DATA_TYPE_MAX_SPEED)) {
                maxSpeed = workout.getMaxSpeed();
            }
            if (hasType(ISportItem.DATA_TYPE_AVG_SPEED_TOTAL_TIME)) {
                long j = DurationUtil.get(workout.getEndTime(), workout.getStartTime());
                totalAvgSpeed = j > 0 ? workout.getDistance() / j : Utils.DOUBLE_EPSILON;
            }
            if (hasType(ISportItem.DATA_TYPE_DURATION)) {
                duration = workout.getDuration();
            }
            if (hasType(ISportItem.DATA_TYPE_TOTAL_DURATION)) {
                totalDuration = DurationUtil.get(workout.getEndTime(), workout.getStartTime());
            }
            if (hasType(ISportItem.DATA_TYPE_PAUSE_DURATION)) {
                long start = workout.getStartTime();
                long end = workout.getEndTime();
                long total = DurationUtil.get(end, start);
                if (total > workout.getDuration()) {
                    pauseDuration = total - workout.getDuration();
                } else {
                    pauseDuration = 0L;
                }
            }

            if (hasType(ISportItem.DATA_TYPE_GRADIENT)) {
                grade = workout.getGrade();
            }
            if (hasType(ISportItem.DATA_TYPE_ELEVATION_GAIN)) {
                elevationGain = workout.getElevationGain();
            }
            if (hasType(ISportItem.DATA_TYPE_ELEVATION_LOSS)) {
                elevationLoss = workout.getElevationLoss();
            }
            if (hasType(ISportItem.DATA_TYPE_CALORIE)) {
                calorie = workout.getCalorie();
            }
            if (hasType(ISportItem.DATA_TYPE_STEP)) {
                steps = workout.getStep();
            }
        }
        if (sourcePoint == null) {
            return;
        }
        if (hasType(ISportItem.DATA_TYPE_SPEED)) {
            speed = sourcePoint.hasWheelData() ? sourcePoint.getCadencePoint().getSpeed() : sourcePoint.getSpeed();
        }
        Double altitude = sourcePoint.getAltitude(null);
        if (sourcePoint.hasPressure() && sourcePoint.hasGps()) {
            altitude = sourcePoint.getGpsPoint().getAltitude();
        }
        if (hasType(ISportItem.DATA_TYPE_ALTITUDE)) {
            this.altitude = altitude;
        }
        if (hasType(ISportItem.DATA_TYPE_TEMPERATURE)) {
            this.temperature= RemoteSharedPreference.getInstance().getInternetTemperature();;
        }
        if (hasType(ISportItem.DATA_TYPE_MAX_ALTITUDE) && altitude != null && (maxAltitude == null || altitude > maxAltitude)) {
            maxAltitude = altitude;
        }
        if (hasType(ISportItem.DATA_TYPE_MIN_ALTITUDE) && altitude != null && (minAltitude == null || altitude < minAltitude)) {
            minAltitude = altitude;
        }
        float elevation = sourcePoint.getElevation();
        SourceDataItem sourceDataItem = elevationGainItem;
        if (sourceDataItem != null && elevation > 0.0f) {
            sourceDataItem.add(elevation);
        }
        if (hasType(ISportItem.DATA_TYPE_AVG_ELEVATION_GAIN) && elevationGainItem != null && elevation > 0.0f) {
            avgElevationGain = (float) elevationGainItem.getAvg();
            Log.d(TAG, "update...avgElevationGain=" + avgElevationGain + ",elevationGainItem=" + elevationGainItem.toString());
        }
        if (elevationLossItem != null && elevation < 0.0f) {
            elevationLossItem.add(elevation);
            Log.d(TAG, "update...elevationLossItem: elevation=" + elevation);
        }
        if (hasType(ISportItem.DATA_TYPE_AVG_ELEVATION_LOSS) && elevationLossItem != null && elevation < 0.0f) {
            avgElevationLoss = -((float) elevationLossItem.getAvg());
            Log.d(TAG, "update...avgElevationLoss=" + avgElevationGain + ",elevationLossItem=" + elevationLossItem.toString());
        }
        if (hasType(ISportItem.DATA_TYPE_MAX_ELEVATION_GAIN) && elevation > 0.0f) {
            if (maxElevationGain == null || elevation > maxElevationGain) {
                maxElevationGain = elevation;
            }
        }
        if (hasType(ISportItem.DATA_TYPE_MAX_ELEVATION_LOSS) && elevation < 0.0f) {
            if  (maxElevationLoss == null || (-elevation) > maxElevationLoss) {
                maxElevationLoss = -elevation;
            }
        }
        GpsPoint gpsPoint = sourcePoint.getGpsPoint();
        if (gpsPoint != null) {
            accuracy = gpsPoint.getAccuracy();
            location = gpsPoint.getLocation();
        }
        CadencePoint cadencePoint = sourcePoint.getCadencePoint();
        if (cadencePoint != null) {
            pressure = cadencePoint.getRealPressure();
            if (hasType(ISportItem.DATA_TYPE_CADENCE)) {
                cadence = cadencePoint.getCadence();
            }
            if (workout != null) {
                if (hasType(ISportItem.DATA_TYPE_AVG_CADENCE)) {
                    avgCadence = workout.getAvgCadence();
                }
                if (hasType(ISportItem.DATA_TYPE_MAX_CADENCE)) {
                    maxCadence = workout.getMaxCadence();
                }
            }
            if (hasType(ISportItem.DATA_TYPE_TEMPERATURE)) {
                //temperature = cadencePoint.getRealTemperature();
            }
            if (hasType(ISportItem.DATA_TYPE_MAX_TEMPERATURE)) {
                float realTemperature = cadencePoint.getRealTemperature();
                if (maxTemperature == null || realTemperature > maxTemperature) {
                    maxTemperature = realTemperature;
                }
            }
            if (hasType(ISportItem.DATA_TYPE_MIN_TEMPERATURE)) {
                float realTemperature2 = cadencePoint.getRealTemperature();
                if (minTemperature == null || realTemperature2 < minTemperature) {
                    minTemperature = realTemperature2;
                }
            }
        }
        HeartratePoint heartratePoint = sourcePoint.getHeartratePoint();
        if (heartratePoint != null) {
            if (hasType(ISportItem.DATA_TYPE_HEART_RATE)) {
                heartrate = heartratePoint.getHeartrate();
            }
            if (workout != null) {
                if (hasType(ISportItem.DATA_TYPE_AVG_HEART_RATE)) {
                    avgHeartrate = workout.getAvgHeartrate();
                }
                if (hasType(ISportItem.DATA_TYPE_MAX_HEART_RATE)) {
                    maxHeartrate = workout.getMaxHeartrate();
                }
            }
            if (hasType(ISportItem.DATA_TYPE_MAX_HEART_RATE_PERCENTAGE)) {
                maxHeartratePer = (float) (heartratePoint.getHeartrate() / maxHeartRateWarning);
            }
        }

        PowerratePoint powerratePoint = sourcePoint.getPowerratePoint();
        if (powerratePoint != null) {
            power = (float) powerratePoint.getPowerrate();
            sourcePoint.setPower(power);
        }

        BiketrainerPoint biketrainerPoint = sourcePoint.getBiketrainerPoint();
        if (biketrainerPoint != null) {
            power = (float) biketrainerPoint.getBiketrainerPower();
            sourcePoint.setPower(power);
            cadence = biketrainerPoint.getBiketrainerCadence();
        }

        IndoorbikePoint indoorbikePoint = sourcePoint.getIndoorbikePoint();
        if (indoorbikePoint != null) {
            speed = (double) indoorbikePoint.getIndoorbikeSpeed();
            cadence =  indoorbikePoint.getIndoorbikeCadence();
            power = (float)indoorbikePoint.getIndoorbikePower();
            indoorbikeresistancelevel = indoorbikePoint.getIndoorbikeResistanceLevel();
            indoorbikeenergy = indoorbikePoint.getIndoorbikeEnergy();
            indoorbiketotaldistance = indoorbikePoint.getIndoorbikeTotalDistance();
            indoorbikeheartrate = indoorbikePoint.getIndoorbikeHeartRate();

            if (workout != null) {
                if (workout.getCalorie() > 0) {
                    calorie = workout.getCalorie();
                }
                if (workout.getDistance() > 0) {
                    distance = workout.getDistance();
                }
            }
        }

        CrosstrainerPoint crosstrainerPoint = sourcePoint.getCrosstrainerPoint();
        if (crosstrainerPoint != null) {
            speed = (double) crosstrainerPoint.getCrosstrainerSpeed();
            crosstrainerstride =  crosstrainerPoint.getCrosstrainerStride();
            crosstrainersteprate =  crosstrainerPoint.getCrosstrainerStepRate();
            cadence =  crosstrainerPoint.getCrosstrainerStepRate();
            power = (float)crosstrainerPoint.getCrosstrainerPower();
            crosstrainerresistancelevel = crosstrainerPoint.getCrosstrainerResistanceLevel();
            crosstrainerenergy = crosstrainerPoint.getCrosstrainerEnergy();
            crosstrainertotaldistance = crosstrainerPoint.getCrosstrainerTotalDistance();
            if (workout != null) {
                if (workout.getCalorie() > 0) {
                    calorie = workout.getCalorie();
                }
                if (workout.getDistance() > 0) {
                    distance = workout.getDistance();
                }
            }
        }

        RowerPoint rowerPoint = sourcePoint.getRowerPoint();
        if (rowerPoint != null) {
            rowerstrokerate =  rowerPoint.getRowerStrokeRate();
            roweravgstrokerate =  rowerPoint.getRowerAvgStrokeRate();
            rowerstrokecount =  rowerPoint.getRowerStrokeCount();
            rowertotaldistance = rowerPoint.getRowerTotalDistance();
            rowerpace = rowerPoint.getRowerPace();
            roweravgpace = rowerPoint.getRowerAvgPace();
            rowerpower = rowerPoint.getRowerPower();
            roweravgpower = rowerPoint.getRowerAvgPower();
            rowerresistancelevel = rowerPoint.getRowerResistanceLevel();
            rowerenergy= rowerPoint.getRowerEnergy();

            if (workout != null) {
                if (workout.getCalorie() > 0) {
                    calorie = workout.getCalorie();
                }
                if (workout.getDistance() > 0) {
                    distance = workout.getDistance();
                }
            }
        }

        if (hasType(ISportItem.DATA_TYPE_POWER)) {
            power = sourcePoint.getPower();
        }
        if (powerItem != null) {
            powerItem.add(sourcePoint.getPower());
        }
        if (hasAnyTypes(ISportItem.DATA_TYPE_AVG_POWER, ISportItem.DATA_TYPE_POWER_TSS)) {
            avgPower = (float) powerItem.getAvg();
        }
        if (hasType(ISportItem.DATA_TYPE_MAX_POWER)) {
            double power = sourcePoint.getPower();
            Log.d(TAG, "update...power=" + power + ", maxPower=" + maxPower);
            if (maxPower == null || power > maxPower) {
                maxPower = (float) power;
            }
        }
        if (powerDataList != null) {
            PowerDataItem powerDataItem = new PowerDataItem(sourcePoint.getPower(), sourcePoint.getTimestamp());
            powerDataList.add(powerDataItem);
            if (powerDataList.size() > 1 && powerDataItem.time - powerDataList.get(0).time > 30000L) { //c.k
                powerDataList.remove(0);
            }
            if (hasType(ISportItem.DATA_TYPE_POWER_3_SECONDS)) {
                avg3sPower = (float) calAvgPower(3000);
            }
            if (hasType(ISportItem.DATA_TYPE_POWER_10_SECONDS)) {
                avg10sPower = (float) calAvgPower(10000);
            }
            if (hasType(ISportItem.DATA_TYPE_POWER_30_SECONDS)) {
                avg30sPower = (float) calAvgPower(30000);
            }
        }
        if (hasType(ISportItem.DATA_TYPE_FTP_PERCENTAGE) && powerFTP != null) {
            powerFTPPer = sourcePoint.getPower() / powerFTP;
        }
        if (hasAnyTypes(ISportItem.DATA_TYPE_POWER_NP, ISportItem.DATA_TYPE_POWER_TSS)) {
            long timestamp = sourcePoint.getTimestamp();
            if (powerTimeNP != null && timestamp - powerTimeNP < 30000L) { //c.k
                powerSectionNP = powerSectionNP + sourcePoint.getPower();
                powerSectionCount = powerSectionCount + 1;
            } else {
                if (powerTimeNP != null) {
                    np4PowerItem.add(Math.pow(powerSectionNP / powerSectionCount, 4.0d));
                    Log.i(TAG, "power NP - " + np4PowerItem.toString());
                    powerNP = (float) Math.pow(np4PowerItem.getAvg(), 0.25d);
                }
                powerTimeNP = timestamp;
                powerSectionCount = 1;
                powerSectionNP = sourcePoint.getPower();
            }
        }
        if (workout != null && hasType(ISportItem.DATA_TYPE_POWER_TSS) && powerFTP != null && powerNP != null) {
            powerTSS = (float) CyclingPowerUtil.calcTSS(DurationUtil.get(workout.getEndTime(),
                    workout.getStartTime()), powerFTP, powerNP, CyclingPowerUtil.calcIF(powerNP, powerFTP));
        }
        //remove not used here
//        hasType(ISportItem.DATA_TYPE_CURRENT_DIRECTION);
//        hasType(ISportItem.DATA_TYPE_CURRENT_AZIMUTH);
    }

    private void clearRealtimeData() {
        speed = null;
        altitude = null;
        cadence = null;
        heartrate = null;
        maxHeartratePer = null;
        power = null;
        biketrainerpower = null;
        indoorbikeresistancelevel = null;
        indoorbiketotaldistance = null;
        indoorbikeenergy = null;
        indoorbikeheartrate = null;
        crosstrainerresistancelevel = null;
        crosstrainertotaldistance = null;
        crosstrainerenergy = null;
        crosstrainerstride = null;
        crosstrainersteprate = null;
        rowerstrokerate= null;
        rowerstrokecount= null;
        roweravgstrokerate= null;
        rowertotaldistance = null;
        rowerpace = null;
        roweravgpace = null;
        rowerpower = null;
        roweravgpower = null;
        rowerresistancelevel = null;
        rowerenergy = null;
        powerFTPPer = null;
        temperature = null;
    }

    public void requestInternetWeatherData() {
        Observable.create(new NetSubscribe(ThirdPartyClient.requestWeatherData(SharedManager.getInstance().getCurLatLngWithMP()))).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).map(new Func1<String, WeatherData>() {
            @Override
            public WeatherData call(String str) {
                try {
                    return new WeatherData(new JSONObject(str));
                } catch (JSONException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable th) {
            }

            @Override
            public void onNext(WeatherData weatherData) {
                Log.v(TAG, "from internet:getTemperature=" + weatherData.getTemperature() );
                RemoteSharedPreference.getInstance().setValue(SPConstant.KEY_WEATHER_TEMPERATURE, (float) weatherData.getTemperature());
            }
        });
    }
    public void init(Workout lastWorkout) {
        Log.d(TAG, "init.....");
        RemoteSharedPreference.getInstance().setValue(SPConstant.KEY_WEATHER_TEMPERATURE, 0.0f);
        requestInternetWeatherData();
        if (hasType(ISportItem.DATA_TYPE_MAX_HEART_RATE_PERCENTAGE)) {
            maxHeartRateWarning = RemoteSharedPreference.getInstance().getHeartRateWarningValue();
        }
        if (hasType(ISportItem.DATA_TYPE_HEART_RATE_LTHT)) {
            User signinUser = App.getContext().getSigninUser();
            if (signinUser != null && signinUser.getPowerHRLT() > 0.0f) {
                heartrateLTHT = signinUser.getPowerHRLT();
            } else {
                heartrateLTHT = 172.0f;
            }
        }
        if (hasAnyTypes(ISportItem.DATA_TYPE_FTP_PERCENTAGE, ISportItem.DATA_TYPE_POWER_TSS)) {
            User signinUser2 = App.getContext().getSigninUser();
            if (signinUser2 != null && signinUser2.getPowerFTP() > 0.0f) {
                powerFTP = signinUser2.getPowerFTP();
            } else {
                powerFTP = 200.0f;
            }
        }
        if (hasAnyTypes(ISportItem.DATA_TYPE_AVG_POWER, ISportItem.DATA_TYPE_POWER_TSS)) {
            powerItem = new SourceDataItem();
        }
        if (hasAnyTypes(ISportItem.DATA_TYPE_AVG_ELEVATION_GAIN)) {
            elevationGainItem = new SourceDataItem();
            Log.d(TAG, "init.....DATA_TYPE_AVG_ELEVATION_GAIN");
        }
        if (hasAnyTypes(ISportItem.DATA_TYPE_AVG_ELEVATION_LOSS)) {
            elevationLossItem = new SourceDataItem();
            Log.d(TAG, "init.....DATA_TYPE_AVG_ELEVATION_LOSS");
        }
        if (hasAnyTypes(ISportItem.DATA_TYPE_POWER_3_SECONDS, ISportItem.DATA_TYPE_POWER_10_SECONDS, ISportItem.DATA_TYPE_POWER_30_SECONDS)) {
            powerDataList = new ArrayList<>();
        }
        if (hasAnyTypes(ISportItem.DATA_TYPE_POWER_NP, ISportItem.DATA_TYPE_POWER_TSS)) {
            np4PowerItem = new SourceDataItem();
            powerSectionNP = 0.0f;
            powerNP = 0.0f;
        }

        if (lastWorkout != null) {
            initFromDB(lastWorkout);
        }
        initialized = true;
    }

    private void initFromDB(Workout lastWorkout) {
        List<Trackpoint> queryTrackPoint;
        Log.d(TAG, "initFromDB...");
        if (powerItem != null) {
            queryDataItem(powerItem, null, "power", lastWorkout.getId());
        }
        if (elevationGainItem != null) {
            queryDataItem(elevationGainItem, "elevation > 0", "elevation", lastWorkout.getId());
            avgElevationGain = (float) elevationGainItem.getAvg();
            Log.d(TAG, "initFromDB...elevationGainItem=" + elevationGainItem.toString());
        }
        if (elevationLossItem != null) {
            queryDataItem(elevationLossItem, "elevation < 0", "elevation", lastWorkout.getId());
            avgElevationLoss = -((float) elevationLossItem.getAvg());
            Log.d(TAG, "initFromDB...elevationLossItem=" + elevationLossItem.toString());
        }
        int i = 0;
        if (np4PowerItem != null && (queryTrackPoint = WorkoutDatabaseHelper
                .queryTrackPoint(new String[]{"power", "time"}, "workoutid=?", new String[]{String.valueOf(lastWorkout.getId())}, null, 0L, 0L)) != null && !queryTrackPoint.isEmpty()) {
            long j = 0;
            double d = Utils.DOUBLE_EPSILON;
            double d2 = Utils.DOUBLE_EPSILON;
            int i2 = 1;
            for (int i3 = 0; i3 < queryTrackPoint.size(); i3++) {
                Trackpoint trackpoint = queryTrackPoint.get(i3);
                if (trackpoint.getTime() - j < 30000L) { //c.k
                    d += trackpoint.getPower();
                    i++;
                } else {
                    if (j > 0) {
                        d2 += Math.pow(d / i, 4.0d);
                        i2++;
                    }
                    j = trackpoint.getTime();
                    d = trackpoint.getPower();
                    i = 1;
                }
            }
            if (d > Utils.DOUBLE_EPSILON) {
                d2 += Math.pow(d / i, 4.0d);
                i2++;
            }
            np4PowerItem.init(d2, i2);
        }
        if (hasType(ISportItem.DATA_TYPE_MAX_ALTITUDE)) {
            maxAltitude = queryMaxMin("altitude", lastWorkout.getId(), true);
        }
        if (hasType(ISportItem.DATA_TYPE_MIN_ALTITUDE)) {
            minAltitude = queryMaxMin("altitude", lastWorkout.getId(), false);
        }
        if (hasType(ISportItem.DATA_TYPE_MAX_ELEVATION_GAIN)) {
            maxElevationGain = (float) queryMaxMin("elevation", lastWorkout.getId(), true);
        }
        if (hasType(ISportItem.DATA_TYPE_MAX_ELEVATION_LOSS)) {
            maxElevationLoss = -((float) queryMaxMin("elevation", lastWorkout.getId(), false));
        }
        if (hasType(ISportItem.DATA_TYPE_MAX_CADENCE)) {
            maxCadence = (int) queryMaxMin("cadence", lastWorkout.getId(), true);
        }
        if (hasType(ISportItem.DATA_TYPE_MAX_TEMPERATURE)) {
            maxTemperature = (float) queryMaxMin("temperature", lastWorkout.getId(), true);
        }
        if (hasType(ISportItem.DATA_TYPE_MIN_TEMPERATURE)) {
            minTemperature = (float) queryMaxMin("temperature", lastWorkout.getId(), false);
        }
        if (hasType(ISportItem.DATA_TYPE_MAX_HEART_RATE)) {
            maxHeartrate = (int) queryMaxMin("heartrate", lastWorkout.getId(), true);
        }
        if (hasType(ISportItem.DATA_TYPE_MAX_POWER)) {
            maxHeartratePer = (float) queryMaxMin("power", lastWorkout.getId(), false);
        }
    }

    private void queryDataItem(SourceDataItem dataItem, String whereCause, String sumColumn, long workoutId) {
        String[] strArr = {"count(id)", "SUM(" + sumColumn + Separators.RPAREN};
        String str = "workoutid=?";
        if (!TextUtils.isEmpty(whereCause)) {
            str = "workoutid=? AND " + whereCause;
        }
        Cursor queryTrackPoint = WorkoutDatabaseHelper.queryTrackPoint(strArr, str, new String[]{String.valueOf(workoutId)}, null, null, 0L, 0L);
        if (queryTrackPoint.moveToFirst()) {
            dataItem.init(queryTrackPoint.getInt(1), queryTrackPoint.getInt(0));
        }
    }

    private double queryMaxMin(String column, long workoutId, boolean max) {
        StringBuilder sb;
        String str;
        String[] strArr = new String[1];
        if (max) {
            sb = new StringBuilder();
            str = "MAX(";
        } else {
            sb = new StringBuilder();
            str = "MIN(";
        }
        sb.append(str);
        sb.append(column);
        sb.append(Separators.RPAREN);
        strArr[0] = sb.toString();
        Cursor queryTrackPoint = WorkoutDatabaseHelper.queryTrackPoint(strArr, "workoutid=?", new String[]{String.valueOf(workoutId)}, null, null, 0L, 0L);
        return queryTrackPoint.moveToFirst() ? queryTrackPoint.getDouble(0) : Utils.DOUBLE_EPSILON;
    }

    private double calAvgPower(int millisecond) {
//        ArrayList<PowerDataItem> arrayList;// = new ArrayList<>();
        boolean isEmpty = powerDataList.isEmpty();
        double d = Utils.DOUBLE_EPSILON;
        if (isEmpty) {
            return Utils.DOUBLE_EPSILON;
        }
        long j = powerDataList.get(powerDataList.size() - 1).time;
        int i = 0;
        for (int size = powerDataList.size() - 1; size >= 0; size--) {
            PowerDataItem powerDataItem = powerDataList.get(size);
            if (j - powerDataItem.time > millisecond) {
                break;
            }
            d += powerDataItem.power;
            i++;
        }
        return d / i;
    }

    public void fillPointData(DisplayPoint displayPoint) {
        displayPoint.reset();
        if (accuracy != null) {
            displayPoint.setAccuracy(accuracy);
        }
        if (pressure != null) {
            displayPoint.setPressure(pressure);
        }
        if (location != null) {
            displayPoint.setLocation(location);
        }
        if (distance != null) {
            displayPoint.setDistance(distance);
        }
        if (speed != null) {
            displayPoint.setSpeed(speed);
        }
        if (indoorbikeresistancelevel != null) {
            displayPoint.setIndoorbikeResistanceLevel(indoorbikeresistancelevel);
        }
        if (indoorbiketotaldistance != null) {
            displayPoint.setIndoorbikeTotalDistance(indoorbiketotaldistance);
        }
        if (indoorbikeenergy != null) {
            displayPoint.setIndoorbikeEnergy(indoorbikeenergy);
        }
        if (indoorbikeheartrate != null) {
            displayPoint.setIndoorbikeHeartRate(indoorbikeheartrate);
            displayPoint.setHeartrate(indoorbikeheartrate);
        }
        if (crosstrainerresistancelevel != null) {
            displayPoint.setCrosstrainerResistanceLevel(crosstrainerresistancelevel);
        }
        if (crosstrainertotaldistance != null) {
            displayPoint.setCrosstrainerTotalDistance(crosstrainertotaldistance);
        }
        if (crosstrainerenergy != null) {
            displayPoint.setCrosstrainerEnergy(crosstrainerenergy);
        }
        if (crosstrainerstride != null) {
            displayPoint.setCrosstrainerStride(crosstrainerstride);
        }
        if (crosstrainersteprate != null) {
            displayPoint.setCrosstrainerSteprate(crosstrainersteprate);
            displayPoint.setCadence(crosstrainersteprate);
        }
        if (rowerstrokerate != null) {
            displayPoint.setRowerStrokeRate(rowerstrokerate);
        }
        if (roweravgstrokerate != null) {
            displayPoint.setRowerAvgStokeRate(roweravgstrokerate);
        }
        if (rowerstrokecount != null) {
            displayPoint.setRowerStrokeCount(rowerstrokecount);
        }
        if (rowertotaldistance != null) {
            displayPoint.setRowerTotalDistance(rowertotaldistance);
        }
        if (rowerpace != null) {
            displayPoint.setRowerPace(rowerpace);
        }
        if (rowerstrokerate != null) {
            displayPoint.setRowerStrokeRate(rowerstrokerate);
            displayPoint.setCadence(rowerstrokerate);
        }
        if (roweravgpace != null) {
            displayPoint.setRowerAvgPace(roweravgpace);
        }
        if (rowerpower != null) {
            displayPoint.setRowerPower(rowerpower);
        }
        if (roweravgpower != null) {
            displayPoint.setRowerAvgPower(roweravgpower);
        }
        if (rowerresistancelevel != null) {
            displayPoint.setRowerResistanceLevel(rowerresistancelevel);
        }
        if (rowerenergy != null) {
            displayPoint.setRowerEnergy(rowerenergy);
        }
        if (avgSpeed != null) {
            displayPoint.setAvgSpeed(avgSpeed);
        }
        if (maxSpeed != null) {
            displayPoint.setMaxSpeed(maxSpeed);
        }
        if (totalAvgSpeed != null) {
            displayPoint.setTotalAvgSpeed(totalAvgSpeed);
        }
        if (duration != null) {
            displayPoint.setDuration(duration);
        }
        if (totalDuration != null) {
            displayPoint.setTotalDuration(totalDuration);
        }
        if (pauseDuration != null) {
            displayPoint.setPauseDuration(pauseDuration);
        }
        if (altitude != null) {
            displayPoint.setAltitude(altitude);
        }
        if (maxAltitude != null) {
            displayPoint.setMaxAltitude(maxAltitude);
        }
        if (minAltitude != null) {
            displayPoint.setMinAltitude(minAltitude);
        }
        if (grade != null) {
            displayPoint.setGrade(grade);
        }
        if (elevationGain != null) {
            displayPoint.setElevationGain(elevationGain);
        }
        if (elevationLoss != null) {
            displayPoint.setElevationLoss(elevationLoss);
        }
//        System.out.println("平均爬升坡度(m): " + avgElevationGain);
        if (avgElevationGain != null) {
            displayPoint.setAvgElevationGain(avgElevationGain);
        }
//        System.out.println(" 平均下降坡度(m): " + avgElevationLoss);
        if (avgElevationLoss != null) {
            displayPoint.setAvgElevationLoss(avgElevationLoss);
        }
//        System.out.println(" 最大爬升坡度(m): " + maxElevationGain);
        if (maxElevationGain != null) {
            displayPoint.setMaxElevationGain(maxElevationGain);
        }
//        System.out.println(" 最大下降坡度(m): " + maxElevationLoss);
        if (maxElevationLoss != null) {
            displayPoint.setMaxElevationLoss(maxElevationLoss);
        }
        if (cadence != null) {
            displayPoint.setCadence(cadence);
        }
        if (avgCadence != null) {
            displayPoint.setAvgCadence(avgCadence);
        }
        if (maxCadence != null) {
            displayPoint.setMaxCadence(maxCadence);
        }
        if (heartrate != null) {
            displayPoint.setHeartrate(heartrate);
        }
        if (avgHeartrate != null) {
            displayPoint.setAvgHeartrate(avgHeartrate);
        }
        if (maxHeartrate != null) {
            displayPoint.setMaxHeartrate(maxHeartrate);
        }
        if (maxHeartratePer != null) {
            displayPoint.setMaxHeartratePer(maxHeartratePer);
        }
        if (heartrateLTHT != null) {
            displayPoint.setHeartrateLTHT(heartrateLTHT);
        }
        if (power != null) {
            displayPoint.setPower(power);
        }
        if (biketrainerpower != null) {
            displayPoint.setPower(biketrainerpower);
        }
        if (avgPower != null) {
            displayPoint.setAvgPower(avgPower);
        }
        if (maxPower != null) {
            displayPoint.setMaxPower(maxPower);
        }
        if (avg3sPower != null) {
            displayPoint.setAvg3sPower(avg3sPower);
        }
        if (avg10sPower != null) {
            displayPoint.setAvg10sPower(avg10sPower);
        }
        if (avg30sPower != null) {
            displayPoint.setAvg30sPower(avg30sPower);
        }
        if (powerFTPPer != null) {
            displayPoint.setPowerFTPPer(powerFTPPer);
        }
        if (powerNP != null) {
            displayPoint.setPowerNP(powerNP);
        }
        if (powerTSS != null) {
            displayPoint.setPowerTSS(powerTSS);
        }
        if (temperature != null) {
            displayPoint.setTemperature(temperature);
        }
        if (maxTemperature != null) {
            displayPoint.setMaxTemperature(maxTemperature);
        }
        if (minTemperature != null) {
            displayPoint.setMinTemperature(minTemperature);
        }
        if (calorie != null) {
            displayPoint.setCalorie(calorie);
        }
        if (steps != null) {
            displayPoint.setSteps(steps);
        }
        if (direction != null) {
            displayPoint.setDirection(direction);
        }
        if (azimuth != null) {
            displayPoint.setAzimuth(azimuth);
        }
    }

    private List<Integer> mPanelItemTypeList;

    private boolean hasType(int type) {
        if (mPanelItemTypeList == null) {
            int sportType = SharedManager.getInstance().getSportType();
            mPanelItemTypeList = PanelItemTypeUtil.loadCache(App.getContext().getUserId(), sportType);
        }
        if (mPanelItemTypeList.contains(type)) {
            return true;
        }
        checkSportType(type);
        return ((typesSwitch >> type) & 1) > 0;
    }

    private boolean hasAnyTypes(int... types) {
        for (int i : types) {
            checkSportType(i);
            if (((typesSwitch >> i) & 1) > 0) {
                return true;
            }
        }
        return false;
    }

    private void checkSportType(int type) {
        if (type > 64) {
            throw new IllegalArgumentException("Sport item type is too long !");
        }
    }
}
